//
//  LGShareManager.m
//  ZCPlatformSDK
//
//  Created by Happy on 6/22/16.
//  Copyright © 2016 ZhanCheng. All rights reserved.
//
#import "LGShareManager.h"
#import "LGThirdDelegate.h"
#import "LGUtils.h"

typedef void(^ZCBShareCallBackType)(NSError *error, NSDictionary *result);

@interface LGShareManager () {
}
@property (nonatomic, copy) ZCBShareCallBackType callback;
@end


@implementation LGShareManager
+ (LGShareManager *)shareInstance {
    static LGShareManager *share = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        share = [[LGShareManager alloc] init];
        
        [LGThirdDelegate sharedInstance].shareCallback = ^(NSError *error, NSDictionary *result, LGShareType shareType) {
            share.callback(error, result);
        };

    });
    return share;
}

#pragma mark - Share Method
- (void)share:(LGShareContent *)shareContent shareType:(LGShareType)shareType callback:(void(^)(NSError *error, NSDictionary *result))callback {
    _callback = callback;
    
    if (shareType == LGShareTypeWeiXin) {
#if ZBShareWeiXinIsOpen
        if (![WXApi isWXAppInstalled]) {
            NSError *noInstallError = [NSError errorWithDomain:@"com.zbsdk.login" code:-2 userInfo:@{NSLocalizedDescriptionKey:@"您还没有安装微信客户端"}];
            callback(noInstallError, nil);
            return;
        }
        if (self.weiXinAppId.length == 0) {
            NSError *weiXinError = [NSError errorWithDomain:@"com.zbsdk.login" code:-1 userInfo:@{NSLocalizedDescriptionKey:@"缺少参数微信appid"}];
            callback(weiXinError, nil);
            return;
        }
        
        [self shareInWeiXin:shareContent];
#else
        NSLog(@"ZCSDK 微信分享暂未开放");
#endif
        
    } else if (shareType == LGShareTypeFacebook) {
#if ZBShareFaceBookIsOpen
        [self shareInFacebook:shareContent];
#else
        NSLog(@"ZCSDK Facebook分享暂未开放");
#endif
    }
}


#pragma mark - 微信分享
#if ZBShareWeiXinIsOpen
- (void)shareInWeiXin:(LGShareContent *)shareContent {
    switch (shareContent.contentType) {
        case LGShareContentTypeText:
            [self weixinShareText:shareContent];
            break;
            
        case LGShareContentTypeImage:
            [self weixinShareImage:shareContent];
            break;
            
        case LGShareContentTypeLink:
            [self weixinShareLink:shareContent];
            break;
            
        case LGShareContentTypeVideo:
            [self weixinShareVideo:shareContent];
            break;
    }
}
- (void)weixinShareText:(LGShareContent *)shareContent {
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.text = shareContent.contentText;
    req.bText = YES;
    req.scene = shareContent.wxScene;
    [WXApi sendReq:req];
}
- (void)weixinShareImage:(LGShareContent *)shareContent {
    NSURL *imageURL = nil;
    
    if ([shareContent.imageURL hasPrefix:@"http"]) {
        imageURL = [NSURL URLWithString:shareContent.imageURL];
    } else {
        imageURL = [NSURL fileURLWithPath:shareContent.imageURL];
    }
    
    /*
     Photos must be less than 12MB in size
     People need the native Facebook for iOS app installed, version 7.0 or higher
     */
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
    if (!image) {
        NSError *error = [NSError errorWithDomain:@"com.zcbsdk.share" code:-3 userInfo:@{NSLocalizedDescriptionKey:@"读取图片失败"}];
        _callback(error, nil);
        return;
    }
    
    WXMediaMessage *message = [WXMediaMessage message];
    
    NSURL *thumbImageUrl = nil;
    if (shareContent.thumbImageURL) { //设置缩略图
        if ([shareContent.thumbImageURL hasPrefix:@"http"]) {
            thumbImageUrl = [NSURL URLWithString:shareContent.thumbImageURL];
        } else {
            thumbImageUrl = [NSURL fileURLWithPath:shareContent.thumbImageURL];
        }
        
    } else {
        thumbImageUrl = imageURL;
        
    }
    UIImage *thumbImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:thumbImageUrl]];
    NSData *thumbDataCompressed = [LGUtils imageCompress:thumbImage targetWidth:160 compression:1.0];
    [message setThumbImage:[UIImage imageWithData:thumbDataCompressed]];
    
    
    if (shareContent.contentTitle) {
        message.title = shareContent.contentTitle;
    }
    if (shareContent.contentDescription) {
        message.description = shareContent.contentTitle;
    }
    
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = UIImagePNGRepresentation(image);
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = shareContent.wxScene;
    [WXApi sendReq:req];
}
// 微信可以显示Title和缩略图
- (void)weixinShareLink:(LGShareContent *)shareContent {
    WXMediaMessage *message = [WXMediaMessage message];
    if (shareContent.contentTitle) {
        message.title = shareContent.contentTitle;
    }
    if (shareContent.contentDescription) {
        message.description = shareContent.contentDescription;
    }
    
    NSData *imageData = nil;
    if (shareContent.thumbImageURL) {
        NSURL *thumbImageURL = nil;
        if ([shareContent.thumbImageURL hasPrefix:@"http"]) {
            thumbImageURL = [NSURL URLWithString:shareContent.thumbImageURL];
        } else {
            thumbImageURL = [NSURL fileURLWithPath:shareContent.thumbImageURL];
        }
        imageData = [NSData dataWithContentsOfURL:thumbImageURL];

    } else {
        UIImage *image = [UIImage imageNamed:@"Icon.png"];
        imageData =  UIImageJPEGRepresentation(image, 1.0);
    }
    
    if (imageData.length > 30000) {
        imageData = [LGUtils imageCompress:[UIImage imageWithData:imageData] targetWidth:50 compression:0.5];
    }
    [message setThumbImage:[UIImage imageWithData:imageData]];
                            
    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = shareContent.contentURL;
    message.mediaObject = webpageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = shareContent.wxScene;
    
    [WXApi sendReq:req];
}
- (void)weixinShareVideo:(LGShareContent *)shareContent {
    NSLog(@"ZCBSDK error:微信分享视频暂未实现");
}
#endif


#pragma mark - Facebook分享
#if ZBShareFaceBookIsOpen
- (void)shareInFacebook:(LGShareContent *)shareContent {
    switch (shareContent.contentType) {
        case LGShareContentTypeText:
            [self facebookShareText:shareContent];
            break;
        case LGShareContentTypeImage:
            [self facebookShareImage:shareContent];
            break;
        case LGShareContentTypeLink:
            [self facebookShareLink:shareContent];
            break;
        case LGShareContentTypeVideo:
            [self facebookShareVideo:shareContent];
            break;
    }
}

- (void)facebookShareText:(LGShareContent *)shareContent {
    NSLog(@"ZCBSDK Error: facebook不能分享纯文本");
}

- (void)facebookShareImage:(LGShareContent *)shareContent {
    NSURL *imageURL = nil;
    
    if ([shareContent.imageURL hasPrefix:@"http"]) {
        imageURL = [NSURL URLWithString:shareContent.imageURL];
    } else {
        imageURL = [NSURL fileURLWithPath:shareContent.imageURL];
    }
    
    /*
     Photos must be less than 12MB in size
     People need the native Facebook for iOS app installed, version 7.0 or higher
     */
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
    if (!image) {
        NSError *error = [NSError errorWithDomain:@"com.zcbsdk.share" code:-3 userInfo:@{NSLocalizedDescriptionKey:@"读取图片失败"}];
        _shareCallback(error, nil);
        return;
    }
    
    FBSDKSharePhoto *photo = [[FBSDKSharePhoto alloc] init];
    photo.image = image;
    photo.userGenerated = YES;
    FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init];
    content.photos = @[photo];
    
    [FBSDKShareDialog showFromViewController:[self currentViewController] withContent:content delegate:[ZCThirdDelegate sharedInstance]];
}

- (void)facebookShareVideo:(LGShareContent *)shareContent {
    FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
    video.videoURL = [NSURL URLWithString:shareContent.videoURL];
    FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
    content.video = video;
    
    [FBSDKShareDialog showFromViewController:nil withContent:content delegate:[ZCThirdDelegate sharedInstance]];
}

//Facebook可以显示缩略图、Title和描述
- (void)facebookShareLink:(LGShareContent *)shareContent {
    FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
    content.contentURL = [NSURL URLWithString:shareContent.contentURL];
    
    if (shareContent.thumbImageURL) { //Facebook分享缩略图只能是网络地址
        content.imageURL = [NSURL URLWithString:shareContent.thumbImageURL];
    }
    if (shareContent.contentTitle) {
        content.contentTitle = shareContent.contentTitle;
    }
    if (shareContent.contentDescription) {
        content.contentDescription = shareContent.contentDescription;
    }
    
    //这种方式无法显示缩略图，只能使用下面方法
    //      [FBSDKShareDialog showFromViewController:[self currentViewController] withContent:content delegate:self];
    
    FBSDKShareDialog *dialog = [[FBSDKShareDialog alloc] init];
    dialog.fromViewController = nil;
    dialog.mode = FBSDKShareDialogModeFeedWeb;
    dialog.shareContent = content;
    dialog.delegate = [ZCThirdDelegate sharedInstance];
    [dialog show];
}
#endif


#pragma mark - Other
- (UIViewController *)currentViewController {
    UIViewController *currentVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    while (currentVC.presentedViewController) {
        currentVC = currentVC.presentedViewController;
    }
    
    return currentVC;
}
@end
